package com.thotran.applockplus.service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.regex.Matcher;

import com.thotran.applockplus.db.DbHelper;

import android.app.ActivityManager;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

public class AppLockPlusService extends Service {

	Timer timer;

	private Context mContext;
	
	private DbHelper mDbHelper;

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		mDbHelper = DbHelper.getInstance(mContext);
		mContext = getApplicationContext();
		testStart();
		return START_STICKY;

	}

	private void testStart() {
		timer = new Timer();
		timer.scheduleAtFixedRate(new TimerTask() {
			@Override
			public void run() {
				getCurrentApp(getApplicationContext());
			}
		}, 0, 1000);
	}

	private void getCurrentApp(Context context) {
		ActivityManager activityManager = (ActivityManager) context
				.getSystemService(Context.ACTIVITY_SERVICE);

		List<ActivityManager.RunningTaskInfo> takeInfo = activityManager
				.getRunningTasks(1);
		ComponentName componentName = takeInfo.get(0).topActivity;
		String packageName = componentName.getPackageName();
		Log.e("packageName", packageName);
		if(mDbHelper.checkExistsApp(packageName))
			Log.e("isstart", packageName);
//			Toast.makeText(context, packageName, Toast.LENGTH_SHORT).show();
	}

	// public static ApkInfo getInfoFromPackageName(String pkgName,
	// Context mContext) {
	// ApkInfo newInfo = new ApkInfo();
	// try {
	// PackageInfo p = mContext.getPackageManager().getPackageInfo(
	// pkgName, PackageManager.GET_PERMISSIONS);
	//
	// newInfo.appname = p.applicationInfo.loadLabel(
	// mContext.getPackageManager()).toString();
	// newInfo.pname = p.packageName;
	// newInfo.versionName = p.versionName;
	// newInfo.versionCode = p.versionCode;
	// newInfo.icon = p.applicationInfo.loadIcon(mContext
	// .getPackageManager());
	// newInfo.setP(p);
	// } catch (NameNotFoundException e) {
	// e.printStackTrace();
	// return null;
	// }
	// return newInfo;
	// }

}
